package com.qmo.edu.mvp.presenter;


import com.google.gson.Gson;
import com.qmo.edu.base.BasePresenter;
import com.qmo.edu.base.ProgressObserver;
import com.qmo.edu.base.RxSchedulers;
import com.qmo.edu.constant.ApiUrl;
import com.qmo.edu.moudle.bean.LoginAskBean;
import com.qmo.edu.moudle.bean.LoginBean;
import com.qmo.edu.moudle.bean.UserInfoNewBean;
import com.qmo.edu.mvp.view.LoginView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.HttpException;

/**
 * Created by ${} on 2019/6/2/002.
 *
 * @author cyx
 */
public class LoginPresenter extends BasePresenter<LoginView> {


    public void login(String userName, String password) {

        LoginAskBean loginAskBean = new LoginAskBean();
        loginAskBean.setAccount(userName);
        loginAskBean.setPassword(password);
        loginAskBean.setAppKey("openauth");
        Gson gson = new Gson();
        String jsonParams = gson.toJson(loginAskBean);

        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);
        mApiService.login(body)
                .compose(RxSchedulers.observableIO2Main(getView()))
                .subscribe(new Observer<LoginBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        getView().showLoading();
                    }

                    @Override
                    public void onNext(LoginBean loginBean) {

                            getView().onLogin(loginBean);

                    }

                    @Override
                    public void onError(Throwable e) {

                        if (e instanceof HttpException) {
                            HttpException httpException = (HttpException) e;
//                            try {
//                                String msg = httpException.response().errorBody().string();
//                                JSONObject jsonObject = new JSONObject(msg);
//                                String errorMsg = jsonObject.getString("invalid_grant");
//                                getView().onError(errorMsg);
//                            } catch (IOException e1) {
//                                e1.printStackTrace();
//                            } catch (JSONException e1) {
//                                e1.printStackTrace();
//                            }
                        }
                    }

                    @Override
                    public void onComplete() {
                        getView().hideLoading();
                    }
                });

    }
}
